/*
** client_bidon.c for  in /home/gomes_m//svn/tek2/zappy-2016-gomes_m/server
** 
** Made by mickael gomes
** Login   <gomes_m@epitech.net>
** 
** Started on  Wed Jul  3 10:16:51 2013 mickael gomes
** Last update Sat Jul 27 14:55:51 2013 mickael gomes
*/

#include		<sys/types.h>
#include		<sys/socket.h>
#include		<stdio.h>
#include		<netdb.h>
#include		<stdlib.h>
#include		<netinet/in.h>
#include		<arpa/inet.h>
#include		<unistd.h>
#include		<string.h>
#include		<sys/wait.h>
#include		<unistd.h>
#include		<stdio.h>
#include		<stdlib.h>

int			server_fd;

int			connect_to_server(int fd, struct sockaddr_in s_in)
{
  if (connect(fd, (struct sockaddr *)&s_in, sizeof(s_in)) == -1)
    {
      close(fd);
      printf("Connect failed.\n");
      return (1);
    }
  return (0);
}

char			*get_cmd()
{
  char			*cmd;
  int			len;

  cmd = malloc(1024);
  len = read(0, cmd, 1024);
  cmd[len] = 0;
  return (cmd);
}

void			init_struct(struct sockaddr_in *s_in, int port, char *ip, int flag)
{
  s_in->sin_family = AF_INET;
  s_in->sin_port = htons(port);
  if (flag == INADDR_ANY)
    s_in->sin_addr.s_addr = flag;
  else
    s_in->sin_addr.s_addr = inet_addr(ip);
}

char			*treat_buff(char *buff)
{
  int			i = 0;

  while (buff[i] && buff[i] != '\n')
    i++;
  buff[i] = 0;
  return (buff);
}

void			server_response(int fd)
{
  char			*buff;
  int			len;

  buff = malloc(1024);
  if ((len = read(fd, buff, 1024)) > 0)
    {
      if (buff[len] != 0)
      	len = read(fd, &buff[len], 1024 - len);
      buff[len] = 0;
      printf("%s", buff);
    }
  free(buff);
}

void			lol(int signal)
{
  write(server_fd, "closing", 8);
}

void			get_signal(int fd)
{
  signal(SIGHUP, lol);
}

int			main(int ac, char **av)
{
  struct sockaddr_in	s_in;
  struct protoent	*pe;
  int			fd;
  int			port;
  char			*ip;
  char			*cmd;

  if (ac != 3)
    {
      printf("Ip and port required\n");
      return (EXIT_FAILURE);
    } 
  ip = av[1];
  port = atoi(av[2]);
  if ((pe = getprotobyname("TCP")) == NULL)
    {
      printf("Getprotobyname has failed.\n");
      return (EXIT_FAILURE);
    }
  if ((fd = socket(AF_INET, SOCK_STREAM, pe->p_proto)) == -1)
    return (EXIT_FAILURE);
  init_struct(&s_in, port, ip, 0);
  if (connect_to_server(fd, s_in))
    return (EXIT_FAILURE);
  server_fd = fd;
  get_signal(fd);
  while (12)
    {
      write(fd, "pwd\n", 5);
      server_response(fd);
      write(1, "$>", 3);
      cmd = get_cmd();
      write(fd, cmd, 512);
      server_response(fd);
    }
  return (EXIT_SUCCESS);
}
